package videosearch;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JPanel;

// Chartpanel helps display a bar graph to visually display where the best match
// occurs in the video
public class ChartPanel extends JPanel {
    private double[] values;

    // constructor takes the values of the matches
    public ChartPanel(double[] v) {
    	updateChart(v);
    }
    
    // updates the chart to normalize the data
    public void updateChart(double[] v){ 
    	for( int i=0;i<v.length;i++ ) { // Out of 100, high value = good
    		v[i] = 100 - ( v[i] / 3.8678159211627432360648678656591 );
	    }	    
	    values = v;
	}

    // Paint component to generate the chart, as well as if it gets rerendered
    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (values == null || values.length == 0) {
            return;
        }
        double minValue = Double.MAX_VALUE; // min and max values for scaling
        double maxValue = Double.MIN_VALUE;
        for (int i = 0; i < values.length; i++) {
            if (minValue > values[i])
                minValue = values[i];
            if (maxValue < values[i])
                maxValue = values[i];
        }

        Dimension d = getSize(); // size of the panel
        int remaining = d.width;
        int clientWidth = d.width;
        int clientHeight = d.height;
        double barWidth = clientWidth / values.length; // width of a bar

        if (maxValue == minValue) {
            return;
        }
        double scale = (clientHeight) / (maxValue - minValue); // scaling
        
        for (int i = 0; i < values.length; i++) { // add the bars to the panel
            int valueX = (int)Math.round(i * barWidth + 1); // increment
            int valueY = 0;
            int height = (int) (values[i] * scale); // based on scale and value
            if (values[i] >= 0)
                valueY += (int) ((maxValue - values[i]) * scale);
            else {
                valueY += (int) (maxValue * scale);
                height = -height;
            }
            
            g.setColor(Color.RED); // red to show up better, then create the bar
            g.fillRect(valueX, valueY, (int)Math.round(barWidth), height);
        }
    }
}

